package com.ruoyi.web.controller.trackApply;


import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.trackapply.ForcastWorkService;
import com.ruoyi.trackapply.domain.ForcastResVO;
import com.ruoyi.trackapply.domain.ForcastWorkParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

@RestController
@RequestMapping("/space/forcast")
@Slf4j
@Api(tags = "典型轨道大气应用-预报效应评估")
public class SpaceForcastController {


    @Autowired
    private ForcastWorkService forcastWorkService;

    @PostMapping("/mate")
    @ApiOperation("计算评估")
    public R<ForcastResVO>  estimate(@RequestBody ForcastWorkParam param) {
        try {
            ForcastResVO estimate = forcastWorkService.estimate(param);
            return R.ok(estimate);
        } catch (Exception e) {
            log.error("计算评估",e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("结果入库")
    @PostMapping("/save")
    public R save(@Validated @RequestBody ForcastWorkParam param) {
        forcastWorkService.save(param);
        return R.ok();
    }

    @ApiOperation("结果下载")
    @PostMapping("/download")
    public void download(@Validated @RequestBody ForcastWorkParam param, HttpServletResponse response) {
        try {
            String txtPath = forcastWorkService.download(param);
            File file = new File(txtPath);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, file.getName());
            FileUtils.writeBytes(file.getAbsolutePath(), response.getOutputStream());
        }catch (Exception e) {
            log.error("下载失败",e);
        }
    }

}
